package com.soundplus.app.shp04.Activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.example.sppmode.BLESPPUtils;
import com.example.sppmode.Common.PairedDeviceInfo;
import com.example.sppmode.DataAccess.MyData;
import com.example.sppmode.OnBluetoothAction;
import com.soundplus.app.shp04.BuildConfig;
import com.example.sppmode.Common.AllParam;
import com.example.sppmode.DataProtocol.CommandInfo;
import com.example.sppmode.DataProtocol.CommandDataAnalyze;
import com.soundplus.app.shp04.DeviceConnectMgr.DevConnMgr;
import com.soundplus.app.shp04.R;
import com.soundplus.app.shp04.databinding.ActivityWelcomeBinding;

import java.util.ArrayList;
import java.util.List;

public class WelcomeActivity extends Activity implements OnBluetoothAction{
    private static final String TAG = "WelcomeActivity";
    private static final String HTAG = "EJV3_UTILS";

    private static final int MSGID_INIT_APP_PARAM = 1;
    private static final int MSGID_EXIT_CURR_ACITVITY = 2;
    private static final int MSGID_EXIT_NEXT_SCENCE = 3;


    private static final int REQUEST_PERMISSION = 1;
    private static final int REQUEST_BT_ENABLE = 2;


    private Context context;
    private ActivityWelcomeBinding binding;
    private MyHandler mHandler;

    private final String[] needPermissions = {
            Manifest.permission.BLUETOOTH,
            Manifest.permission.BLUETOOTH_ADMIN,
//            Manifest.permission.BLUETOOTH_CONNECT,
//            Manifest.permission.BLUETOOTH_SCAN,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            //Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS,
    };

    private final List<String> lackPermissionList = new ArrayList<>();

    private EditText inputText;
    private Button sendButton;
    private TextView reciveText;
    private Button nextSceceButton;
    BLESPPUtils blesppUtils;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        binding = ActivityWelcomeBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        mHandler = new MyHandler(context, getMainLooper());
        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSGID_INIT_APP_PARAM), 100);

        binding.tvVersion.setText(" V" + BuildConfig.VERSION_NAME);

        if (AllParam.showLogo) {
            binding.ivLogo.setVisibility(View.VISIBLE);
            binding.tvLogo.setVisibility(View.INVISIBLE);
        } else {
            binding.ivLogo.setVisibility(View.INVISIBLE);
            binding.tvLogo.setVisibility(View.VISIBLE);
        }
        permissionCheck();

//        taiic_actor
        blesppUtils  = new BLESPPUtils(context, this);
        blesppUtils.enableBlvetooth();

        inputText = findViewById(R.id.inputText);
        sendButton = findViewById(R.id.button2);
        reciveText = findViewById(R.id.textView);

        reciveText.setMovementMethod(new ScrollingMovementMethod());
        nextSceceButton = findViewById(R.id.button3);
//send value
        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String strValue = inputText.getText().toString();
                blesppUtils.send(strValue);

            }
        });
//        button to change next scence
        nextSceceButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                blesppUtils.disConnectedBtDevice();

                MyData.getInstance();
                AllParam.initAllParam();
                DevConnMgr.getInstance().init(context.getApplicationContext());
                mHandler.sendMessageDelayed(mHandler.obtainMessage(MSGID_EXIT_NEXT_SCENCE), 1000);

            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Log.d(TAG, "onActivityResult, requestCode=" + requestCode + " resultCode=" + resultCode);
        if (requestCode == REQUEST_BT_ENABLE) {
            if (resultCode != Activity.RESULT_OK) {
                WelcomeActivity.this.finish();
            }
        }
    }

    @SuppressLint("MissingPermission")
    @Override
    protected void onResume() {
        super.onResume();
        if (!BluetoothAdapter.getDefaultAdapter().isEnabled()) {
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, REQUEST_BT_ENABLE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.d(TAG, "onRequestPermissionsResult, requestCode=" + requestCode);

        if (requestCode == REQUEST_PERMISSION) {
            boolean lackPermission = false;

            for (int result : grantResults) {
                if (result == PackageManager.PERMISSION_DENIED) {
                    lackPermission = true;
                    break;
                }
            }
            if (lackPermission) {
                Toast.makeText(context, R.string.lack_permission_prompt, Toast.LENGTH_LONG).show();
                mHandler.sendMessageDelayed(mHandler.obtainMessage(MSGID_EXIT_CURR_ACITVITY), 5000);
            } else {
                mHandler.sendMessageDelayed(mHandler.obtainMessage(MSGID_EXIT_CURR_ACITVITY), 1000);
            }
        }
    }

    private void permissionCheck() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            lackPermissionList.clear();
            for (String permission : needPermissions) {
                if (ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_DENIED) {
                    lackPermissionList.add(permission);
                }
            }

            if (lackPermissionList.size() > 0) {
                String[] lackPermissions = new String[lackPermissionList.size()];
                for (int i = 0; i < lackPermissionList.size(); i++) {
                    lackPermissions[i] = lackPermissionList.get(i);
                }
                requestPermissions(lackPermissions, REQUEST_PERMISSION);
            } else {
                Log.d(HTAG, "permissionCheck: ");
                mHandler.sendMessageDelayed(mHandler.obtainMessage(MSGID_EXIT_CURR_ACITVITY), 2000);
            }

        } else {
            mHandler.sendMessageDelayed(mHandler.obtainMessage(MSGID_EXIT_CURR_ACITVITY), 1000);
        }
    }

    @Override
    public void onFoundDevice(BluetoothDevice device) {

    }

    @Override
    public void onConnectSuccess(BluetoothDevice device) {
        Log.d(HTAG, "onConnectSuccess: "+ device.getAddress());
        reciveText.append(HTAG + " onConnectSuccess" + device.getAddress() + "\r\n");
        reciveText.append(HTAG + " onConnectSuccess" + device.getName() + "\r\n");

    }

    @Override
    public void onDisConnect(BluetoothDevice device) {
        Log.d(HTAG, "onDisConnect: " + device.getAddress());
        reciveText.append(HTAG + " onDisConnect " + device.getAddress() + "\r\n");

    }

    @Override
    public void onReceiveBattery(String[] bytes, int battery, BLESPPUtils.BatteryStatus batteryStatus) {
        Log.d(HTAG, "onReceiveBattery: "+ battery);
        reciveText.append(HTAG + " onReceiveBattery " + battery + "\r\n");
    }

    @Override
    public void onReceiveUseMode(String[] bytes, int useMode) {
        Log.d(HTAG, " onReceiveUseMode: " + useMode);
        reciveText.append(HTAG + " onReceiveUseMode " + useMode + "\r\n");
    }

    @Override
    public void onReceiveLabel(String[] bytes, int label) {
        Log.d(HTAG, "onReceiveLabel: "+ label);
        reciveText.append(HTAG + " onReceiveLabel " + label + "\r\n");
    }


    @Override
    public void onReceiveCame(Bitmap bitmap, int width, int height) {
        Log.d(HTAG, "onReceiveCame: "+ width + " " + height);
        reciveText.append(HTAG + " onReceiveCame " + width + " " + height + "\r\n");

    }

    @Override
    public void onSendBytes(byte bytes) {
        Log.d(HTAG, "onSendBytes: " + bytes);
        reciveText.append(HTAG + " onSendBytes " + bytes + "\r\n");
    }

    @Override
    public void onFinishFoundDevice() {

    }

    @Override
    public void onConnectedDevice(BluetoothDevice device) {

    }

//    MyThread myThread = new MyThread(this);
    private class MyHandler extends Handler {
        Looper looper;

        public MyHandler(Context context, Looper looper) {
            super(looper);
            this.looper = looper;
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSGID_INIT_APP_PARAM:
                    initAppParam();





//                    myThread.start();
                    break;
                case MSGID_EXIT_CURR_ACITVITY:
//                    connect bluetooth
                    blesppUtils.setBtDeviceName("TAIIC_EJ_V3");
                    blesppUtils.getconnectedBtDevice();

                    break;

                case MSGID_EXIT_NEXT_SCENCE:
                    exitWelcome();
                    break;
            }
        }
    }



//    int devConnStatus = DataConfig.STATE_DISCONNECTED;
    private void initAppParam() {
//        blesppUtils.enableBlvetooth();
//        blesppUtils.setBtDeviceName("TAIIC_EJ_V3");
//        blesppUtils.getconnectedBtDevice();



    }


//    private SPPEventListener sppEventListener = new SPPEventListener() {
//        @Override
//        public void onConnStatusChanged(int status) {
//            Log.d(TAG, "onConnStatusChanged status=" + status);
//            if (status == SppConnMgr.SPP_CONNECTED)
//            {
//                devConnStatus = DataConfig.STATE_CONNECTED;
//            }
//
//            else if (status == SppConnMgr.SPP_DISCONNECTED)
//                devConnStatus = DataConfig.STATE_DISCONNECTED;
//
//        }
//
//        @Override
//        public void onRecvData(byte[] data, int dataLen) {
//            Log.d(TAG, "onRecvData, dataLen=" + dataLen);
//
//        }
//    };

    private void exitWelcome() {
        Intent intent;
        intent = new Intent(WelcomeActivity.this, MainActivity.class);

        startActivity(intent);
        WelcomeActivity.this.finish();
    }


}
